package com.project.m.api.busi.handlers.hicatcard.Inner;

import com.project.m.api.busi.bean.inner.InnerCardPresentReq;
import com.project.m.api.busi.bean.inner.InnerCardPresentResp;
import com.project.m.api.busi.config.BusiError;
import com.project.m.api.busi.db.entity.hicatcard.card.TCard;
import com.project.m.api.busi.db.entity.hicatcard.card.TCardService;
import com.project.m.api.busi.db.entity.hicatcard.user.TUser;
import com.project.m.api.busi.db.entity.hicatcard.user.TUserCard;
import com.project.m.api.busi.db.entity.hicatcard.user.TUserCardService;
import com.project.m.api.busi.db.service.hicatcard.card.CardService;
import com.project.m.api.busi.db.service.hicatcard.card.CardServiceService;
import com.project.m.api.busi.db.service.hicatcard.user.UserCardService;
import com.project.m.api.busi.db.service.hicatcard.user.UserService;
import com.project.m.api.busi.handlers.MerchantBizParamChecker;
import com.project.m.api.busi.util.IdGenerator.IdGenerator;
import com.project.m.api.validates.ValidateParam;
import com.project.m.api.validates.ValidateRet;
import com.project.m.api.validates.ValidateType;
import com.project.m.api.validates.ValidateUtil;
import com.project.m.api.busi.util.TimeUtil;
import com.project.m.api.common.biz.BizHandler;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class InnerCardPresentBizHandler extends MerchantBizParamChecker<InnerCardPresentReq, InnerCardPresentResp>
        implements BizHandler<InnerCardPresentReq, InnerCardPresentResp> {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    CardService cardService;

    @Autowired
    UserService userService;

    @Autowired
    UserCardService userCardService;

    @Autowired
    CardServiceService cardServiceService;

    @Override
    public InnerCardPresentResp handle(InnerCardPresentReq bizRequest) throws Exception {

        InnerCardPresentResp bizResp = new InnerCardPresentResp();

        try {
            ValidateRet vRet = checkParam(bizRequest, bizResp);
            if (!vRet.isValid()) {
                return bizResp;
            }

            //用户是否存在
            List<TUser> userList = userService.findByPhoneAndEnable(bizRequest.getPhone(), true);
            if (CollectionUtils.isEmpty(userList)) {
                bizResp.setResult_code(BusiError.ERR_CODE_USER_NONE);
                bizResp.setError_message(BusiError.ERR_MSG_USER_NONE);
                return bizResp;
            }

            TUser user = userList.get(0);

            //卡片是否存在
            TCard card = cardService.findByCardId(bizRequest.getCardId());
            if (card == null) {
                bizResp.setResult_code(BusiError.ERR_CODE_CARD_NOT_EXIST);
                bizResp.setError_message(BusiError.ERR_MSG_CARD_NOT_EXIST);
                return bizResp;
            }

            //可能要加 TUserCardRecharge

            //加卡片和service
            List<TUserCard> userCardList = new ArrayList<TUserCard>();
            List<TUserCardService> userCardServiceList = new ArrayList<TUserCardService>();
            for (int i = 0; i < bizRequest.getNumber(); i++) {
                TUserCard userCard = new TUserCard();
                userCard.setUserId(user.getUserId());
                userCard.setCardId(card.getCardId());
                userCard.setUserCardNumber(IdGenerator.generateOrderId(IdGenerator.ORDERID_PREFIX_USER_CARD, "00", "0000"));
                userCard.setSource(TUserCard.SOURCE_COMPANY_PRESENT);
                userCard.setSourceUserId(null);
                userCard.setStatus(TUserCard.STATUS_ACTIVE);
                userCard.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
                userCard.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
                Integer effectiveDay = card.getEffectiveDay();
                String endTime = TimeUtil.getFormatTime(TimeUtil.addDateNDay(new Date(), effectiveDay), TimeUtil.DATE_PATTERN_NOSEPARTOR);
                endTime = StringUtils.substring(endTime, 0, endTime.length() - 6) + "235959";
                userCard.setEndTime(endTime);
                userCardList.add(userCard);
            }

            userCardList = userCardService.saveUserCardList(userCardList);

            for (TUserCard userCard : userCardList) {
                List<TCardService> cardServiceList = cardServiceService.findByCardIdAndEnable(userCard.getCardId(), true);
                for (TCardService cardService : cardServiceList) {
                    TUserCardService userCardService = new TUserCardService();
                    userCardService.setUserCardId(userCard.getUserCardId());
                    userCardService.setServiceId(cardService.getServiceId());
                    userCardService.setServiceTime(cardService.getServiceTime());
                    userCardService.setStatus("1");
                    userCardService.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
                    userCardService.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
                    userCardService.setEnable(true);
                    userCardServiceList.add(userCardService);
                }
            }
            userCardService.saveUserCardServiceList(userCardServiceList);
            bizResp.setResult_code(BusiError.ERR_CODE_SUCCESS);
            bizResp.setError_message("");
            return bizResp;
        } catch (Exception e) {
            logger.error("InnerCardListQueryBizHandler", e);
            bizResp.setResult_code(BusiError.ERR_CODE_DB_SAVE);
            bizResp.setError_message(BusiError.ERR_MSG_DB_SAVE);
            return bizResp;
        }

    }

    @Override
    public ValidateRet checkParam(InnerCardPresentReq req, InnerCardPresentResp resp) {
        ValidateRet vRet = super.checkParam(req, resp);
        if (!vRet.isValid())
            return vRet;
        List<ValidateParam> paramList = new ArrayList<ValidateParam>();
        paramList.add(new ValidateParam("phone", ValidateType.NOTBLANK, req.getPhone()));
        paramList.add(new ValidateParam("number", ValidateType.NOTBLANK, req.getNumber()));
        paramList.add(new ValidateParam("cardId", ValidateType.NOTBLANK, req.getCardId()));


        vRet = ValidateUtil.validate(paramList);
        if (vRet == null) {
            vRet = new ValidateRet(true, "");
        }

        if (!vRet.isValid()) {
            resp.setResult_code(BusiError.ERR_CODE_PARAM_BAD_REQ);
            resp.setError_message(vRet.getErrMsg());
        }

        return vRet;
    }
}
